import { useEffect, useState } from 'react'
import { getCurrent } from '@tauri-apps/api/window'

// 检查是否在Tauri环境中运行
const isTauri = typeof window !== 'undefined' && window.__TAURI__ !== undefined

// 获取窗口名称的函数，兼容网页和Tauri环境
async function getWindowName(): Promise<string> {
  if (isTauri) {
    try {
      const currentWindow = await getCurrent()
      return currentWindow.label
    } catch (error) {
      console.error('获取Tauri窗口名称失败:', error)
      return 'main'
    }
  }
  return 'main' // 在网页环境中默认使用'main'
}

// 缓存窗口名称，避免重复获取
let cachedWindowName: string | null = null

// 同步获取窗口名称的函数
function getWindowNameSync(): string {
  if (cachedWindowName) {
    return cachedWindowName
  }
  return 'main' // 默认返回'main'，后续会异步更新
}

// 初始化窗口名称
if (isTauri) {
  getWindowName().then(name => {
    cachedWindowName = name
  }).catch(() => {
    cachedWindowName = 'main'
  })
} else {
  cachedWindowName = 'main'
}

export function getItem(key: string) {
  const windowName = getWindowNameSync()
  const storage = windowName === 'main' ? localStorage : sessionStorage
  const config = JSON.parse(storage.getItem(`${windowName}-config`) ?? '{}')
  return config[key]
}

export function setItem(key: string, value: any) {
  const windowName = getWindowNameSync()
  const storage = windowName === 'main' ? localStorage : sessionStorage
  const config = JSON.parse(storage.getItem(`${windowName}-config`) ?? '{}')
  config[key] = value
  storage.setItem(`${windowName}-config`, JSON.stringify(config))
}

export function clear() {
  const windowName = getWindowNameSync()
  const storage = windowName === 'main' ? localStorage : sessionStorage
  storage.clear()
}

export const useStorage = <T>(
  key: string,
  initialValue: T
): [T, (value: T) => void] => {
  function getStoredValue() {
    const value = getItem(key)
    if (value) {
      return value
    }
    return initialValue
  }
  const [storedValue, setStoredValue] = useState<T>(getStoredValue)

  useEffect(() => {
    const item = getItem(key)
    if (item) {
      setStoredValue(item)
    }
  }, [key])

  const setValue = (value: T) => {
    // Save state
    setStoredValue(value)
    // Save to Storage
    setItem(key, value)
  }
  return [storedValue, setValue]
}
